/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package servlet;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author hmardones
 */
public class DownloadImage extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String patente = request.getParameter("patente");
        String filePath = FileUploadHandler.UPLOAD_DIRECTORY + File.separator+patente +".jpg";
        File f = new File(filePath);
        ServletContext context  = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(filePath);
        response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
        response.setContentLength( (int)f.length() );
        response.setHeader( "Content-Disposition", "inline; filename=\"" + "" + "\"" );

            int length   = 0;
            ServletOutputStream op = null;
            try {
                    op = response.getOutputStream();
            } catch (IOException e1) {
                    return;
            }
                        
            byte[] bbuf = new byte[1024];
                 DataInputStream in = null;
            try {
                    in = new DataInputStream(new FileInputStream(f));
            } catch (FileNotFoundException e) {
                    return;
            }
            try {
                    while ((in != null) && ((length = in.read(bbuf)) != -1))
                    {
                    op.write(bbuf,0,length);
                    }
            } catch (IOException e) {
                    return;
            }

            try {
                    in.close();
                    op.flush();
                    op.close();
            } catch (IOException e) {
                    return;
            }

        
    }    
}
